//----------------------------------------------------------------------------
//  Copyright (C) 2004-2012 by EMGU. All rights reserved.       
//----------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Threading;

using Emgu.CV;
using Emgu.CV.UI;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.CV.VideoSurveillance;

namespace VideoSurveilance
{
    public partial class VideoSurveilance : Form
    {
        private static MCvFont _font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_SIMPLEX, 1.0, 1.0);
        private static BlobTrackerAuto<Bgr> _tracker;
        private static IBGFGDetector<Bgr> _detector;

        private IPCamera m_ipcam1 = new JPEG_IPCamera();
        private IPCamera m_ipcam2 = new JPEG_IPCamera();

        public VideoSurveilance()
        {
            InitializeComponent();
            _detector = new FGDetector<Bgr>(FORGROUND_DETECTOR_TYPE.FGD);
            _tracker = new BlobTrackerAuto<Bgr>();

            m_ipcam1.NewFrame += ProcessFrame1;
            m_ipcam2.NewFrame += ProcessFrame2;

            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(frmMain_FormClosing);
            this.Load += new EventHandler(frmMain_Load);           
        }

        private void frmMain_Load(object sender, System.EventArgs e)
        {
            m_ipcam1.URLSRC = "http://www.tripcheck.com/RoadCams/cams/i5capitol_pid556.jpg";
            m_ipcam2.URLSRC = "http://www.tripcheck.com/RoadCams/cams/i5macadam_pid566.jpg";
        }

        void frmMain_FormClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            m_ipcam1.NewFrame -= ProcessFrame1;
            m_ipcam2.NewFrame -= ProcessFrame2;

            // Waiting for terminating local threads
            m_ipcam1.Dispose();
            m_ipcam2.Dispose();
        }

        void updateImg(ImageBox img , Image<Bgr, Byte> frame)
        {
            MethodInvoker actione = delegate
            {
                img.Image = frame;
            };
            img.BeginInvoke(actione);
        }

        void ProcessFrame1(object sender, CameraEventArgs e)
        {
            updateImg(imageBox1, e.Bitmap);            
        }

        void ProcessFrame2(object sender, CameraEventArgs e)
        {
            updateImg(imageBox2, e.Bitmap);            
        }
    }
}